package com.core.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * @author : HUANG
 * @create : 2025/6/1 17:16
 * @function :
 */
@Slf4j
public class IdGeneratorSnowFlake {

    // 机器id
    private static long workerId = 0;
    // 数据中心id
    private static long dataCenterId = 1;

    private static Snowflake snowflake;

    static {
        snowflake = IdUtil.createSnowflake(workerId, dataCenterId);
        try {
            workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        } catch (Exception e) {
            e.printStackTrace();
            log.info("当前机器ID失败", e);
            workerId = NetUtil.getLocalhostStr().hashCode();
        }
    }

    public static synchronized long snowFlakeId() {
        return snowflake.nextId();
    }

    public static synchronized long snowFlakeId(long workerId, long dataCenterId) {
        Snowflake snowflake = IdUtil.createSnowflake(workerId, dataCenterId);
        return snowflake.nextId();
    }
}
